/**
 * Created by apple on 2017/12/19.
 */
var DBFactory = require('../db/mysql_db');
var async = require('async');
var UserFreezeMoneytDao = module.exports;

//data={uid,app_sid,unfreeze_sid}
UserFreezeMoneytDao.unfreezeMoney = function (data, cb) {
    if(!data.uid || !data.app_sid || !data.unfreeze_sid) return cb('参数有误');
    DBFactory.getConnection(function(error, connection) {
        if(error) return cb(error);
        async.waterfall([

            function (callback) {
                connection.beginTransaction(function(err) {
                    callback(err);
                });
            },

            //查找对应的解冻key
            function (callback) {
                var sql = 'SELECT * FROM unfreeze_condition WHERE sid = ? AND app_sid = ? ';
                connection.query(sql,[data.unfreeze_sid,data.app_sid],function (err,result) {
                    var unfreezeInfo = (result && result.length > 0) ? result[0] : undefined;
                    if(!unfreezeInfo) {
                        unfreezeInfo = {
                            sub_sids:data.unfreeze_sid
                        }
                    }
                    callback(null, unfreezeInfo);
                });
            },

            //去查询所有key对应的待冻结金额
            function (unfreezeInfo,callback) {
                var unfreezeSids = unfreezeInfo.sub_sids.split(',');
                var sql = 'SELECT * FROM freeze_money_record WHERE uid = ? AND app_sid = ? AND status = 0 AND unfreeze_sid IN ? ';

                connection.query(sql,[data.uid,data.app_sid,[unfreezeSids]],function (err,result) {
                    if(err){
                        console.log('解冻金额时SELECT freeze_money_record ERR:' + err);
                        callback('解冻金额时获取冻结金额ERR:' + err);
                        return;
                    }
                    var freezeRecords = (result && result.length > 0) ? result : undefined;
                    var unfreezeInfos = {
                        freezeRecords:freezeRecords,
                    }
                    callback(null,unfreezeInfos);
                });
            },

            //没有待解冻金额，直接跳过; 有的话，查找余额表
            function (unfreezeInfos,callback) {
                if(!unfreezeInfos.freezeRecords) return callback(null,unfreezeInfos);
                var sql = 'SELECT money,freeze_money FROM user_app_new_agent WHERE uid = ? AND app_sid = ? ';
                connection.query(sql,[data.uid,data.app_sid],function (err,result) {
                    if(err){
                        console.log('解冻金额时SELECT user_app_new_agent ERR:' + err);
                        callback('解冻金额时SELECT user_app_new_agent ERR:' + err);
                        return;
                    }
                    var userMoney = (result && result.length > 0) ? result[0] : undefined;
                    if(!userMoney) {
                        console.log('解冻金额时SELECT user_app_new_agent ERR:' + err);
                        callback('解冻金额时获取用户信息ERR:' + err);
                        return;
                    }
                    unfreezeInfos.originalMoney = userMoney.money ? userMoney.money : 0;
                    unfreezeInfos.original_freeze_money = userMoney.freeze_money ? userMoney.freeze_money : 0;
                    callback(null,unfreezeInfos);
                });
            },

            //没有待解冻金额，直接跳过; 有的话，构造余额记录，并进行解冻
            function (unfreezeInfos,callback) {
                if(!unfreezeInfos.freezeRecords) return callback(null,unfreezeInfos);
                var ids = [];
                var totalMoney = 0;
                var userMoneyLogs = [];
                unfreezeInfos.freezeRecords.forEach(function (unfreezeInfo) {
                    ids.push(unfreezeInfo.id);
                    var moneyLog = [];
                    moneyLog.push(unfreezeInfo.id);
                    moneyLog.push(data.uid);
                    moneyLog.push(unfreezeInfos.originalMoney + totalMoney);
                    moneyLog.push(unfreezeInfo.money);
                    moneyLog.push(data.app_sid);
                    moneyLog.push(unfreezeInfo.comment + '(解锁)');
                    moneyLog.push(0);
                    moneyLog.push(unfreezeInfo.type);
                    userMoneyLogs.push(moneyLog);
                    totalMoney += unfreezeInfo.money;
                });
                unfreezeInfos.ids = ids;
                unfreezeInfos.userMoneyLogs = userMoneyLogs;
                var sql = 'UPDATE user_app_new_agent SET money = money + ? ,score = score + ?, ';
                var value = [totalMoney,totalMoney];
                if(unfreezeInfos.original_freeze_money - totalMoney <= 0){
                    sql += 'freeze_money = 0 ';
                }else {
                    sql += 'freeze_money = freeze_money - ? ';
                    value.push(totalMoney);
                }
                sql += 'WHERE uid = ? AND app_sid = ? ';
                value.push(data.uid,data.app_sid);
                connection.query(sql,value,function (err,result) {
                    if(err){
                        console.log('解冻金额时UPDATE user_app_new_agent ERR:' + err);
                        callback('解冻金额时修改金额ERR:' + err);
                        return;
                    }
                    if(result.affectedRows > 0){
                        callback(null,unfreezeInfos);
                        return;
                    }
                    callback('操作失败');
                });
            },

            //没有待解冻金额，直接跳过; 有的话，解冻金额
            function (unfreezeInfos,callback) {
                if(!unfreezeInfos.freezeRecords) return callback(null,unfreezeInfos);
                var sql = 'UPDATE freeze_money_record SET status = 1, unfreeze_time = ? where id IN ? ';
                var time = new Date();
                connection.query(sql,[time,[unfreezeInfos.ids]],function (err,result) {
                    if(err){
                        console.log('解冻金额时UPDATE freeze_money_record ERR:' + err);
                        callback('解冻金额时解冻金额ERR:' + err);
                        return;
                    }
                    if(result.affectedRows > 0){
                        callback(null,unfreezeInfos);
                        return;
                    }
                    callback('操作失败');
                });
            },

            //没有待解冻金额，直接跳过; 有的话，插入余额记录表
            function (unfreezeInfos,callback) {
                if(!unfreezeInfos.freezeRecords) return callback(null,'无待解冻金额');
                var sql = 'INSERT INTO user_money (`order_id`,`uid`,`original_money`,`money`,`app_sid`,`comment`,`sign`,`type`) VALUES ? ';
                connection.query(sql,[unfreezeInfos.userMoneyLogs],function (err,result) {
                    if(err){
                        console.log('解冻金额时INSERT freeze_money_record ERR:' + err);
                        callback('解冻金额时记录ERR:' + err);
                        return;
                    }
                    if(result.affectedRows > 0){
                        callback(null,unfreezeInfos);
                        return;
                    }
                    callback('操作失败');
                });
            }


        ],function (err,unfreezeInfos) {
            if(err){
                connection.rollback(function () {
                    connection.release();
                    cb(err);
                });
            }else {
                connection.commit(function (e) {
                    if(e){
                        connection.rollback(function () {
                            connection.release();
                            cb(e);
                        });
                    } else {
                        connection.release();
                        cb(null, unfreezeInfos);
                    }
                });
            }
        });

    });

}